import FileSaver from 'file-saver';
import { saveDecoratePages, getPageCustomDetail } from '@/api/basisMG';
export default {
  data () {
    return {
      containerProperties: new Map()
    };
  },
  created () {
    this.containerProperties.set('singleContainer', {
      component: 'singleContainer',
      text: '单个容器',
      type: '1-1',
      active: true,
      containerNumber: 1,
      proportions: [1],
      containerType: 1, // 1 single 2 mutiEquaContainer 3 unMutiEquaContainer
      style: 'setting'
    });

    this.containerProperties.set('mutiEquaContainer', {
      component: 'mutiEquaContainer',
      text: '均分容器',
      type: '1-1',
      active: true,
      containerNumber: 2,
      proportions: [1 / 2, 1 / 2],
      containerType: 2,
      style: 'setting'
    });

    this.containerProperties.set('unMutiEquaContainer', {
      component: 'unMutiEquaContainer',
      text: '不均分容器',
      type: '1-1',
      active: true,
      proportions: [33 / 100, 67 / 100],
      containerType: 3,
      containerNumber: 2,
      style: 'setting'
    });

    this.containerProperties.set('recommendContainer', {
      component: 'recommendContainer',
      text: '四大高手',
      type: '1-1',
      active: true,
      proportions: [237 / 324, 87 / 324], // 占屏幕比例
      containerType: 3,
      containerNumber: 2,
      tabs: [
        {
          text: '同步高手',
          ratio: '1',
          direction: '0',
          type: 'container',
          name: 'synch'
        },
        {
          text: '专项高手',
          type: 'container',
          ratio: '1',
          direction: '0',
          name: 'special'
        },
        {
          text: '提分高手',
          ratio: '1',
          direction: '0',
          type: 'container',
          name: 'raise'
        },
        {
          text: '素养高手',
          ratio: '1',
          direction: '0',
          type: 'container',
          name: 'attainment'
        }
      ],
      style: 'headerinformationstyle'
    });
    
    this.containerProperties.set('firstclassPage', {
      component: 'firstclassPage',
      text: '专项分类',
      type: '1-1',
      active: true,
      proportions: [249 /648, 399 / 648], // 占屏幕比例
      containerType: 3,
      containerNumber: 2,
      tabs: [
        {
          text: '学科标题',
          ratio: '1',
          direction: '0',
          type: 'container',
          name: 'sync'
        },
      ],
      style: 'headerinformationstyle'
    });

    this.containerProperties.set('specialContainer', {
      component: 'specialContainer',
      text: '专项容器',
      type: '1-1',
      active: true,
      proportions: [1], // 占屏幕比例
      containerType: 5,
      containerNumber: 1,
      specialTabs: [
        {
          title: '同步学习',
          name: 'specialTab',
          icon:'',
          tabs: [],
          abstract: {
            component: "specialContainerTab",
            text: "专项容器组件",
            style: "recoment_tab_style1",
            setStyle: {},
            ratio: "1.00"
          }
        }
      ],
      style: 'headerinformationstyle'
    });
  },
  methods: {
    catJson () {
      const { containerJson, containerList } = this.handleDataList(this.dataList);
      const JsonData = {
        id: this.id,
        pname: this.pageSetup.pname,
        templateJson: this.pageSetup,
        containerJson: containerJson,
        containers: containerList
      };
      this.$alert(`<textarea class="jsonArea">${this.formatJson(JSON.stringify(JsonData))}</textarea>`, '查看JSON', {
        confirmButtonText: '确定',
        customClass: 'JSONView',
        dangerouslyUseHTMLString: true,
        callback: () => {}
      });
      console.log('逆向数据----', this.reverseHandList(JsonData));
    },
    // 正向输出处理
    handleDataList (list) {
      const handleList = list.length > 0 ? this.getNewTree(this.dataList) : [];
      let containerJson = {};
      let containerList = [];
      if (!handleList || handleList.length === 0) {
        return { containerJson, containerList };
      }
      const container = handleList[0].setStyle;
      if (container.component === 'singleContainer') {
        containerList = [
          {
            ratio: '1',
            direction: '0',
            components: handleList[0].components || []
          }
        ];
      } else if (container.component === 'specialContainer') {
        containerList = this.handlerCompontents(handleList[0].components || []);
      } else {
        containerList = this.handlerCompontents(handleList[0].components || []);
      }
      containerJson = {
        ...handleList[0].setStyle,
        name: handleList[0].name,
        type: handleList[0].type
      };
      return { containerJson, containerList };
    },
    handlerReverseComponent (components) {
      if (components.length === 0) {
        return [];
      }
      return components.map((item, index) => {
        if (item.components && item.components.length > 0 && item.components[0].extras) {
          const abstract = {
            component: item.components[0].component,
            text: item.components[0].text,
            style: item.components[0].style,
            ratio: item.components[0].ratio
          };
          const json = {
            text: item.text,
            direction: item.direction,
            type: 'containers',
            ratio: item.ratio,
            abstract: abstract,
            group: item.group,
            components: item.components[0].extras
          };
          return json;
        } else {
          item.group = item.group;
          return item;
        }
      });
    },
    handlerCompontents (components) {
      if (components.length === 0) {
        return [];
      }
      return components.map((item, index) => {
        if (item.abstract) {
          const component = {
            component: item.abstract.component,
            text: item.abstract.text,
            style: item.abstract.style,
            ratio: item.abstract.ratio,
            extras: item.components
          };
          const json = {
            text: item.text,
            direction: item.direction,
            type: 'containers',
            ratio: item.ratio,
            group: item.group,
            components: [component]
          };
          return json;
        } else {
          item.group = item.group;
          return item;
        }
      });
    },
    // 逆向回显处理
    reverseHandList (JsonData) {
      const { id, name, containerJson, containers } = JsonData;
      let rcontainerList = [];
      if (containerJson.component === 'singleContainer') {
        rcontainerList = containers[0].components;
      } else {
        const list = this.handlerReverseComponent(containers);
        console.log('this.handlerReverseComponent(containers)', this.handlerReverseComponent(containers));
        rcontainerList = this.getReverseTree(list);
      }
      const handleList = [
        {
          list: rcontainerList,
          name: containerJson.name,
          setStyle: containerJson
        }
      ];
      return { handleList };
    },
    getNewTree (tree) {
      return tree.map((item) => {
        const aa = JSON.parse(JSON.stringify(item));
        delete aa.list;
        let components = [];
        if (item.list && item.list.length > 0) {
          components = this.getNewTree(item.list);
        }
        let json = {
          ...aa,
          components: components
        };
        return json;
      });
    },
    getReverseTree (tree) {
      return tree.map((item) => {
        const aa = JSON.parse(JSON.stringify(item));
        delete aa.components;
        let list = [];
        if (item.components && item.components.length > 0) {
          list = this.getReverseTree(item.components);
        }
        let json = {
          ...aa,
          list: list
        };
        return json;
      });
    },
    /**
     * @description: 格式化JSON数据
     * @param {*} jsonObj
     * @Author: ckk
     * @Date: 2022-09-05 15:42:44
     * @return {*}
     */
    transitionJsonToString (jsonObj) {
      // 转换后的jsonObj受体对象
      // let _jsonObj: any = null; // ts写法
      let _jsonObj = null;
      // 判断传入的jsonObj对象是不是字符串，如果是字符串需要先转换为对象，再转换为字符串，这样做是为了保证转换后的字符串为双引号
      if (Object.prototype.toString.call(jsonObj) !== '[object String]') {
        try {
          _jsonObj = JSON.stringify(jsonObj);
        } catch (error) {
          // 转换失败错误信息
          // callback(error);
        }
      } else {
        try {
          jsonObj = jsonObj.replace(/(\')/g, '"');
          _jsonObj = JSON.stringify(JSON.parse(jsonObj));
        } catch (error) {
          // 转换失败错误信息
          // callback(error);
        }
      }
      return _jsonObj;
    },
    /**
     * @description: 格式化json
     * @param {*} jsonObj
     * @Author: ckk
     * @Date: 2022-09-05 15:43:39
     * @return {*}
     */
    formatJson (jsonObj) {
      // 正则表达式匹配规则变量
      let reg = null;
      // 转换后的字符串变量
      let formatted = '';
      // 换行缩进位数
      let pad = 0;
      // 一个tab对应空格位数
      let PADDING = '\t';
      // json对象转换为字符串变量
      let jsonString = this.transitionJsonToString(jsonObj);
      if (!jsonString) {
        return jsonString;
      }
      // 存储需要特殊处理的字符串段
      let _index = [];
      // 存储需要特殊处理的“再数组中的开始位置变量索引
      let _indexStart = null;
      // 存储需要特殊处理的“再数组中的结束位置变量索引
      let _indexEnd = null;
      // 将jsonString字符串内容通过\r\n符分割成数组
      let jsonArray = [];
      // 正则匹配到{,}符号则在两边添加回车换行
      jsonString = jsonString.replace(/([\{\}])/g, '\r\n$1\r\n');
      // 正则匹配到[,]符号则在两边添加回车换行
      jsonString = jsonString.replace(/([\[\]])/g, '\r\n$1\r\n');
      // 正则匹配到,符号则在两边添加回车换行
      jsonString = jsonString.replace(/(\,)/g, '$1\r\n');
      // 正则匹配到要超过一行的换行需要改为一行
      jsonString = jsonString.replace(/(\r\n\r\n)/g, '\r\n');
      // 正则匹配到单独处于一行的,符号时需要去掉换行，将,置于同行
      jsonString = jsonString.replace(/\r\n\,/g, ',');
      // 特殊处理双引号中的内容
      jsonArray = jsonString.split('\r\n');
      jsonArray.forEach(function (node, index) {
        // 获取当前字符串段中"的数量
        let num = node.match(/\"/g) ? node.match(/\"/g).length : 0;
        // 判断num是否为奇数来确定是否需要特殊处理
        if (num % 2 && !_indexStart) {
          _indexStart = index;
        }
        if (num % 2 && _indexStart && _indexStart != index) {
          _indexEnd = index;
        }
        // 将需要特殊处理的字符串段的其实位置和结束位置信息存入，并对应重置开始时和结束变量
        if (_indexStart && _indexEnd) {
          _index.push({
            start: _indexStart,
            end: _indexEnd
          });
          _indexStart = null;
          _indexEnd = null;
        }
      });
      // 开始处理双引号中的内容，将多余的"去除
      _index.reverse().forEach(function (item, index) {
        let newArray = jsonArray.slice(item.start, item.end + 1);
        jsonArray.splice(item.start, item.end + 1 - item.start, newArray.join(''));
      });
      // 将处理后的数组通过\r\n连接符重组为字符串
      jsonString = jsonArray.join('\r\n');
      // 将匹配到:后为回车换行加大括号替换为冒号加大括号
      jsonString = jsonString.replace(/\:\r\n\{/g, ':{');
      // 将匹配到:后为回车换行加中括号替换为冒号加中括号
      jsonString = jsonString.replace(/\:\r\n\[/g, ':[');
      // 将上述转换后的字符串再次以\r\n分割成数组
      jsonArray = jsonString.split('\r\n');
      // 将转换完成的字符串根据PADDING值来组合成最终的形态
      jsonArray.forEach(function (item, index) {
        let i = 0;
        // 表示缩进的位数，以tab作为计数单位
        let indent = 0;
        // 表示缩进的位数，以空格作为计数单位
        let padding = '';
        if (item.match(/\{$/) || item.match(/\[$/)) {
          // 匹配到以{和[结尾的时候indent加1
          indent += 1;
        } else if (item.match(/\}$/) || item.match(/\]$/) || item.match(/\},$/) || item.match(/\],$/)) {
          // 匹配到以}和]结尾的时候indent减1
          if (pad !== 0) {
            pad -= 1;
          }
        } else {
          indent = 0;
        }
        for (i = 0; i < pad; i++) {
          padding += PADDING;
        }
        formatted += padding + item + '\r\n';
        pad += indent;
      });
      // 返回的数据需要去除两边的空格和换行
      return formatted.trim().replace(new RegExp('^\\' + '<br />' + '+|\\' + '<br />' + '+$', 'g'), '');
    },
    // 导出json
    exportJSON () {
      // 将json转换成字符串
      const data = JSON.stringify({
        id: this.id,
        pname: this.pageSetup.pname,
        templateJson: JSON.stringify(this.pageSetup),
        component: JSON.stringify(this.dataList)
      });
      const blob = new Blob([data], { type: '' });
      FileSaver.saveAs(blob, `${this.pageSetup.pname}.json`);
    },
    // 导入json
    importJSON () {
      const file = document.getElementById('file').files[0];
      const reader = new FileReader();
      reader.readAsText(file);
      const _this = this;
      reader.onload = function () {
        try {
          // this.result为读取到的json字符串，需转成json对象
          const ImportJSON = JSON.parse(this.result);
          console.log('ImportJSON----', ImportJSON);
          // 检测是否导入成功
          // 导入JSON数据
          _this.id = ImportJSON.id;
          _this.pageSetup = JSON.parse(ImportJSON.templateJson);
          _this.dataList = JSON.parse(ImportJSON.component);
          console.log('ImportJSON----', ImportJSON.component);
        } catch (error) {
          // console.log('导入数据个数错误');
          _this.$message({
            type: 'warnning',
            message: '导入数据错误'
          });
        }
      };
    },
    //保存页面装修
    async savePageJson () {
      const { containerJson, containerList } = this.handleDataList(this.dataList);
      this.pageformdata.pageId = this.$route.query.id;
      this.pageSetup.subjectCode = this.$route.query.subjectCode;
      console.log('containerList---', containerList);
      this.pageformdata.pageContent = JSON.stringify({
        templateJson: JSON.stringify(this.pageSetup),
        // component: JSON.stringify(this.pageComponents),
        containerJson: JSON.stringify(containerJson),
        containers: JSON.stringify(containerList)
      });

      const data = await saveDecoratePages(this.pageformdata);
      if (data.code != 200) {
        return this.$message.error(data.message);
      } else {
        this.$message.success(data.message);
        this.dialogFormVisible = false;
        // this.$router.go(-1);
      }
    },
    //获取页面装修详情
    async getPageCustomDetail () {
      const detailformdata = {
        pageId: this.$route.query.id,
        version: ''
      };
      const res = await getPageCustomDetail(detailformdata);
      const _this = this;
      if (res.data) {
        _this.pageSetup = JSON.parse(JSON.parse(res.data.pageContent).templateJson);
        // _this.pageComponents = JSON.parse(JSON.parse(res.data.pageContent).component);
        const jsonData = {
          containerJson: JSON.parse(JSON.parse(res.data.pageContent).containerJson),
          containers: JSON.parse(JSON.parse(res.data.pageContent).containers)
        };

        console.log(this.reverseHandList(jsonData));

        _this.dataList = this.reverseHandList(jsonData).handleList;
        // _this.newIdarr = JSON.parse(res.data.pageContent).resid;
        _this.pageformdata.id = res.data.id;
        _this.pageformdata.note = res.data.note;
      }
    }
  }
};
